package com.wa.mp.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wa.mp.beans.Employee;
import com.wa.mp.mapper.EmployeeMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Notes
 * @Author gary
 * @Date 2021/5/18 14:59
 **/
@Service
public class EmployeeService extends ServiceImpl<EmployeeMapper, Employee> {

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_UNCOMMITTED, rollbackFor = Exception.class)
    public Employee syncStudent(String name, CountDownLatch downLatch, AtomicBoolean state) {
        downLatch.countDown();
        while (state.get()) {
        }
        Employee employee = selectByName(name);
        Console.log(Thread.currentThread().getName() + " 查询 时间" + DateUtil.current());
        if (employee != null) {
            return employee;
        }
        synchronized (EmployeeService.class) {
            employee = selectByName(name);
            Console.log(Thread.currentThread().getName() + " 进入锁查询 时间" + DateUtil.current());
            if (employee != null) {
                return employee;
            }
            employee = this.save(name);
        }
        return employee;
    }

    public Employee save(String name) {
        Employee employee = selectByName(name);
        Console.log(Thread.currentThread().getName() + " 保存查询 时间" + DateUtil.current());
        if (employee != null) {
            throw new RuntimeException("该" + name + "已存在");
        } else {
            Employee save = new Employee();
            save.setLastName(name);
            this.save(save);
            Console.log(Thread.currentThread().getName() + " 保存 时间" + DateUtil.current());
            return save;
        }
    }

    public Employee selectByName(String name) {
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        employeeLambdaQueryWrapper.eq(Employee::getLastName, name);
        List<Employee> list = this.list(employeeLambdaQueryWrapper);
        if (list.size() == 0) {
            return null;
        }
        return list.get(0);
    }
}
